package com.brutal.paint;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.text.DecimalFormat;

import com.rsbuddy.script.methods.Skills;

public class PaintProgressBar {

	private final int skill;
	private final int x;
	private final int y;
	private final int width;
	private final int height;

	public PaintProgressBar(int skill, int x, int y, int w, int h) {
		this.skill = skill;
		this.x = x;
		this.y = y;
		width = w;
		height = h;
	}

	private void drawTextWithShadow(Graphics2D g, String s, Font f, int x, int y) {
		final Color fg = new Color(255, 255, 255), shadow = Color.BLACK;
		g.setFont(f);
		g.setColor(shadow);
		g.drawString(s, x + 1, y + 1);
		g.setColor(fg);
		g.drawString(s, x, y);
	}

	private void drawStyledBox(Graphics2D g, int x, int y, int w, int h) {
		g.setColor(new Color(25, 25, 25, 150));
		g.fillRect(x, y + h / 2, w, h / 2);
		g.setColor(new Color(255, 255, 255, 66));
		g.fillRect(x, y, w, h / 2);
		g.setColor(new Color(0, 0, 0));
		g.drawRect(x, y, w, h);
	}

	private double getPercentToNextLevel(final int index) {
		DecimalFormat df = new DecimalFormat("##.##");
		int lvl = Skills.getRealLevel(index);
		if (lvl == 99 && index != Skills.DUNGEONEERING) {
			return 0;
		} else if (lvl == 120 && index == Skills.DUNGEONEERING) {
			return 0;
		}
		double xpTotal = Skills.XP_TABLE[lvl + 1] - Skills.XP_TABLE[lvl];
		if (xpTotal == 0) {
			return 0;
		}
		double xpDone = Skills.getCurrentExp(index) - Skills.XP_TABLE[lvl];
		double progress = 100 * xpDone / xpTotal;
		return Double.valueOf(df.format(progress));
	}

	public void onRepaint(Graphics g1) {
		Graphics2D g = (Graphics2D) g1;
		final Font font = new Font("Arial", 0, 9);
		FontMetrics fm = g.getFontMetrics(font);
		String text = getPercentToNextLevel(skill) + "% To Level "
				+ (Skills.getRealLevel(skill) + 1);
		Rectangle bounds = fm.getStringBounds(text, g).getBounds();
		g.setColor(new Color(0, 255, 0, 150));
		g.fillRect(x, y, (int) (getPercentToNextLevel(skill) * (width / 100)),
				height);
		g.setColor(new Color(255, 0, 0, 150));
		g.fillRect(x + (int) (getPercentToNextLevel(skill) * (width / 100)), y,
				width - (int) (getPercentToNextLevel(skill) * (width / 100)),
				height);
		drawStyledBox(g, x - width / 80, y - width / 80, width + (width / 40),
				height + (width / 40));
		drawTextWithShadow(g, text, font, x - bounds.x
				+ ((width - bounds.width) / 2), y - bounds.y
				+ ((height - bounds.height) / 2));
	}
}
